package com.snow.controller.admin;

import com.github.pagehelper.PageInfo;
import com.snow.constant.ErrorConstant;
import com.snow.constant.Types;
import com.snow.constant.Webconst;
import com.snow.controller.BaseController;
import com.snow.exception.SiteException;
import com.snow.pojo.dto.AttachDto;
import com.snow.pojo.model.AttachDomain;
import com.snow.pojo.model.UserDomain;
import com.snow.qiniu.QiniuService;
import com.snow.service.attach.AttachService;
import com.snow.utils.ApiResponse;
import com.snow.utils.Commons;
import com.snow.utils.TaleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-31
 **/
@Api("附件页")
@Controller
@RequestMapping("/admin/attach")
public class AttachController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AttachController.class);
    public static final String CLASSPATH = TaleUtils.getUploadFilePath();
    @Autowired
    private AttachService attachService;
    @Autowired
    private Commons commons;
    @Autowired
    private QiniuService qiniuService;
    @ApiOperation("进入文件管理页")
    @GetMapping("")
    public String index(
            @ApiParam(name="pageNum",value="页数",required = false)
            @RequestParam(name="pageNum",required = false,defaultValue = "1")
            Integer pageNum,
            @ApiParam(name="limit",value="每页多少条",required = false)
            @RequestParam(name="limit",required = false,defaultValue = "15")
            Integer limit,
            Model model
    ){

        PageInfo<AttachDto> attaches = attachService.getAttaches(pageNum, limit);
        model.addAttribute("attachs",attaches);
        model.addAttribute(Types.ATTACH_URL.getType(), Commons.site_option(Types.ATTACH_URL.getType(),Commons.site_url()));
        model.addAttribute("commons",commons);
        model.addAttribute("max_file_size",Webconst.MAX_FILE_SIZE/1024);
        return "admin/attach";
    }

    @PostMapping("/uploadfile")
    @ResponseBody
    @ApiOperation("markdown文件上传")
    public void upload(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name="editormd_image_file",value="文件数组",required = true)
            @RequestParam(name="editormd-image-file",required = true)
            MultipartFile file
    ){
        logger.info("AttachController uploadFiles======>");
        try {
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type","text/html");
            String fileName = file.getOriginalFilename().replaceFirst("/","");
            logger.info("originalFileName is:" + file.getOriginalFilename());
            String fkey = qiniuService.upload(file, fileName);
            System.out.println("/uploadfile ====>fkey =" + fkey);
            AttachDomain attachDomain = new AttachDomain();
            attachDomain.setFkey(fkey);
            attachDomain.setFname(fileName);
            attachDomain.setFtype(TaleUtils.isImage(file.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType());
            attachService.addAttach(attachDomain);
            response.getWriter().write( "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"" + attachDomain.getFkey() + "\"}" );

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @ApiOperation("多文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public void uploadBatch(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "files",value="文件数组",required =true)
            @RequestParam(name="files",required = true)
            MultipartFile [] files
    ){
        try{
            request.setCharacterEncoding("utf-8");
            response.setHeader("content-type","html/text");
//            Subject subject = SecurityUtils.getSubject();
//            UserDomain user = (UserDomain) subject.getSession().getAttribute(Webconst.LOGIN_SESSION_KEY);
//            Integer uid = user.getUid();
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename().replaceFirst("/","");
                qiniuService.upload(file,fileName);
                AttachDomain attachDomain = new AttachDomain();
                attachDomain.setAuthorId(1);
                attachDomain.setFkey(qiniuService.URL + fileName);
                attachDomain.setFname(fileName);
                attachDomain.setFtype(TaleUtils.isImage(file.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType());
                attachService.addAttach(attachDomain);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    @PostMapping("delete")
    @ResponseBody
    @ApiOperation("删除文件记录")
    public ApiResponse delete(
            @ApiParam(name="id",value="文件ID",required = true)
            @RequestParam(name="id",required = true)
            Integer id
    ){
        AttachDto attach = attachService.getAttachById(id);
        if(attach == null){
            throw SiteException.withErrorCode(ErrorConstant.Att.DELETE_ATT_FAIL);
        }
        attachService.deleteAttach(id);
        return ApiResponse.success();
    }


}
